package com.wisdom.benefit.jufa.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatEditText;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.base.BaseApplication;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.utils.CountDownTimerUtils;

import androidx.core.content.ContextCompat;
import cn.ycbjie.ycstatusbarlib.StatusBarUtils;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {
    private Button loginBtn;
    private TextView sendVerTv;
    @SuppressLint("StaticFieldLeak")
    public static LoginActivity mInstance;
    private AppCompatEditText accountEt, passwordEt;
    private String account, password;


    @Override
    protected int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInstance = this;
        //设置状态栏为蓝色
        YCAppBar.setStatusBarColor(LoginActivity.this,
                ContextCompat.getColor(LoginActivity.this,
                        R.color.white));
//        状态栏亮色模式，设置状态栏黑色文字、图标
        StatusBarUtils.StatusBarLightMode(LoginActivity.this);
    }





    @Override
    protected void initViews() {
        //登录
        loginBtn = findViewById(R.id.login_btn);
        //发送验证码
        sendVerTv = findViewById(R.id.send_verification_code);
        //账号
        accountEt = findViewById(R.id.et_account);
        //密码
        passwordEt = findViewById(R.id.et_pwd);
        //设置监听
        setCick();
    }

    private void setCick() {
        //登录
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(accountEt.getText().toString(), passwordEt.getText().toString());
            }
        });
        //发送验证码
        sendVerTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(sendVerTv
                        , 60000, 1000);
                mCountDownTimerUtils.start();
            }
        });
        //账号
        accountEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (accountEt.getText().equals("请输入账号") || TextUtils.isEmpty(accountEt.getText())) {
                    loginBtn.setEnabled(false);
                } else if (passwordEt.getText().equals("请输入密码") || TextUtils.isEmpty(passwordEt.getText())) {
                    loginBtn.setEnabled(false);
                } else {
                    account = String.valueOf(accountEt.getText());
                    loginBtn.setEnabled(true);
                }
            }
        });

        //密码
        passwordEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (accountEt.getText().equals("请输入账号") || TextUtils.isEmpty(accountEt.getText())) {
                    loginBtn.setEnabled(false);
                } else if (passwordEt.getText().equals("请输入密码") || TextUtils.isEmpty(passwordEt.getText())) {
                    loginBtn.setEnabled(false);
                } else {
                    password = String.valueOf(passwordEt.getText());
                    loginBtn.setEnabled(true);
                }
            }
        });
    }

    @Override
    protected int getTitleStringRes() {
        return 0;
    }

    /**
     * 账号密码登陆
     */
    private void login(String userName, String password) {
        String deviceId = DeviceInfoModel.getDeviceId(LoginActivity.this);
        BaseApplication.getContext().setDeviceId(deviceId);
        showProgressDialog("正在登录");
        addDisposable(RetrofitService.getNetService()
                .login(userName, password,deviceId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        BaseApplication.getContext().setUserId(response.getData().toString());
                        //步骤1：创建一个SharedPreferences对象
                        SharedPreferences sharedPreferences= getSharedPreferences("data",Context.MODE_PRIVATE);
                        //步骤2： 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        //步骤3：将获取过来的值放入文件
                        editor.putString("isHaveLogin", "1");
                        editor.putString("userId", response.getData().toString());
                        //步骤4：提交
                        editor.commit();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("登录失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }


}
